package utils.security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

public class AESUtil {

    private static String defaultKeyValue = "centerservice3.0";

    private static final String DEFAULT_CHARSET = "UTF-8";

    public static final String KEY_ALGORITHM = "AES";

    public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";

    private static AESUtil aes256Util = null;


    private AESUtil() {}


    public static Key toKey() throws Exception {

        SecretKey secretKey = new SecretKeySpec(defaultKeyValue.getBytes(), KEY_ALGORITHM);

        return secretKey;
    }

    public static String encrypt(String src) throws Exception {
        return new Base64().encode(encrypt(src.getBytes(DEFAULT_CHARSET)));
    }


    public static byte[] encrypt(byte[] data) throws Exception {
        Key k = toKey();
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
        cipher.init(Cipher.ENCRYPT_MODE, k);
        return cipher.doFinal(data);
    }


    public static String decrypt(String src) throws Exception {
        return new String(decrypt(new Base64().decode(src)), DEFAULT_CHARSET);
    }

    public static byte[] decrypt(byte[] data) throws Exception {
        Key k = toKey();
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM, "BC");
        cipher.init(Cipher.DECRYPT_MODE, k);
        return cipher.doFinal(data);
    }


    public static void main(String[] args) throws Exception {
        String str = "芸sweet12213213";
        //打印原文
        System.out.println("原文：" + str);
        //打印密文
        System.out.print("加密后：");
        String aesStr = encrypt(str);
        System.out.print(aesStr);
        //解密密文
        String decrypt = decrypt(aesStr);
        //打印原文
        System.out.println("解密后：" + decrypt);
    }
}
